package com.ag.score.service;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 服务器 修改 配置  https://www.jianshu.com/p/490e2981545c
 */
public class WsocketServer {
    private static final Logger LOG = LoggerFactory.getLogger(WsocketServer.class);
    public void start(int beginPort, int nPort) {
        LOG.debug("WsocketServer starting....");

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);

            bootstrap.childHandler(new NioWebSocketChannelInitializer());


            for (int i = beginPort; i <= nPort; i++) {
                int port =  i;
                bootstrap.bind(port).addListener((ChannelFutureListener) future -> {
                    LOG.debug("bind success in port: " + port);
                });
            }
        }catch(Exception e){
            e.printStackTrace();
            LOG.debug("WsocketServer error!"+e.getMessage());
        }
        LOG.debug("WsocketServer started!");
    }
}
